package com.scedu.controller;

import com.scedu.config.ProjectUrlConfig;
import com.scedu.config.WechatMpConfig;
import com.scedu.enums.ResultEnums;
import com.scedu.exception.SellException;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/*
微信接口
 */

@Controller
@RequestMapping("/wechat")
@Slf4j
public class WechatController {
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private WxMpService wxOpenService;
    @Autowired
    private ProjectUrlConfig projectUrlConfig;

    @GetMapping("/authorize")
    public  String authorize(@RequestParam("returnUrl") String returnUrl){

        //1.配置参数
        //2.调用方法
        String url=projectUrlConfig.getWechatMpAuthorize()+"/sell/wechat/userInfo";
        String redirectUrl="";
        try{
        redirectUrl=wxMpService.oauth2buildAuthorizationUrl(url,
                WxConsts.OAuth2Scope.SNSAPI_USERINFO,
                URLEncoder.encode(returnUrl,"UTF-8"));}
        catch (UnsupportedEncodingException e){
            log.error("转码失败，结果{}",e.getMessage());
            throw new SellException(ResultEnums.WX_MP_ERROR.getCode(),e.getMessage());
        }
        log.info("微信网页授权生成url 结果{}",redirectUrl);
        return "redirect:"+redirectUrl;
    }
    @GetMapping("/userInfo")
    public  String  userInfo(@RequestParam("code") String code,
                           @RequestParam("state") String redirectUrl){
        log.info("微信网页授权 code={}", code);
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken =new WxMpOAuth2AccessToken();
        try {
            wxMpOAuth2AccessToken=  wxMpService.oauth2getAccessToken(code);
        }catch (WxErrorException errorException){
            log.error("微信网页授权错误，{}",errorException.getError().getErrorMsg());
            throw new SellException(ResultEnums.WX_MP_ERROR.getCode(),errorException.getMessage());
        }
        String openId=wxMpOAuth2AccessToken.getOpenId(); //获取openid
        WxMpUser wxMpUser =new WxMpUser();
        try {
            wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
        }catch (WxErrorException errorException){
            log.error("微信网页授权错误，{}",errorException.getError().getErrorMsg());
            throw new SellException(ResultEnums.WX_MP_ERROR.getCode(),errorException.getMessage());
        }

         log.info("微信网页授权获取个人信息={}", wxMpUser.toString());
        return "redirect:"+redirectUrl+"?openid="+openId;

    }
    /*
    微信开放平台登录
     */
    @GetMapping("/qrauthorize")
    public  String qrAuthorize(@RequestParam("returnUrl") String returnUrl){

        //1.配置参数
        //2.调用方法
        String url=projectUrlConfig.getWechatOpenAuthorize()+"/sell/wechat/qruserInfo";
        String redirectUrl="";
        try{
            redirectUrl=wxOpenService.buildQrConnectUrl(url,
                    WxConsts.QrConnectScope.SNSAPI_LOGIN, //网页应用目前仅填写snsapi_login即可
                    URLEncoder.encode(returnUrl,"UTF-8"));}
        catch (UnsupportedEncodingException e){
            log.error("转码失败，结果{}",e.getMessage());
            throw new SellException(ResultEnums.WX_MP_ERROR.getCode(),e.getMessage());
        }
        log.info("微信网页授权生成url 结果{}",redirectUrl);
        return "redirect:"+redirectUrl;
    }

    @GetMapping("/qruserInfo")
    public  String  qrUserInfo(@RequestParam("code") String code,
                             @RequestParam(value = "state",required = false) String redirectUrl){
        log.info("微信网页授权 code={}", code);
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken =new WxMpOAuth2AccessToken();
        try {
            wxMpOAuth2AccessToken=  wxOpenService.oauth2getAccessToken(code);
        }catch (WxErrorException errorException){
            log.error("微信网页授权错误，{}",errorException.getError().getErrorMsg());
            throw new SellException(ResultEnums.WX_MP_ERROR.getCode(),errorException.getMessage());
        }
        String openId=wxMpOAuth2AccessToken.getOpenId(); //获取openid
        WxMpUser wxMpUser =new WxMpUser();
        try {
            wxMpUser = wxOpenService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
        }catch (WxErrorException errorException){
            log.error("微信网页授权错误，{}",errorException.getError().getErrorMsg());
            throw new SellException(ResultEnums.WX_MP_ERROR.getCode(),errorException.getMessage());
        }
        redirectUrl="http://wxdemo.heyishe.cn/sell/seller/login"; //借用账号写死返回地址
        log.info("微信网页授权获取个人信息={}", wxMpUser.toString());
        return "redirect:"+redirectUrl+"?openid="+openId;

    }

}
